<template>
	<view class="">
		<u-navbar :custom-back="back" backIconColor="#000" title="订单支付" titleColor="#000" :borderBottom="false"
			:background="{background: '#fff'}"></u-navbar>
		<view style="width: 702rpx;border-radius: 16rpx;"
			class="flex flex-column align-center justify-center bg-white u-m-24">
			<view class="font-36 flex  align-center u-m-t-30">
				<text style="font-size:52rpx"> ￥{{pay_price}}</text>
			</view>
			<view class="flex align-center u-p-b-20">
				<text class="u-p-y-20 u-p-r-30" style="color:#9C9C9F">剩余支付时间:</text>
				<u-count-down ref="uCountDown" bgColor="#fff" color="#9C9C9F" fontSize="24" :timestamp="timestamp"
					@end="end"></u-count-down>
			</view>
			<!-- <view class="u-p-b-30" v-else>
				<text>订单支付已经超时, {{time}}秒后自动返回</text>
			</view> -->
		</view>
		<view class=" u-p-y-34 u-m-t-24 u-p-l-24 bg-white u-m-l-24" v-for="(item, index) in list" :key="index"
			style="width: 702rpx;border-radius: 16rpx;">
			<view class="flex justify-between  align-center" @click="value = index" style="width: 100%;">
				<view class="flex align-center">
					<view class="flex">
						<!-- <image style="width: 48px;height: 48px;" src="/static/goods/jifen@2x.png" mode="" /> -->
						<u-icon v-if="item == '余额支付'" :name="$_BASE_IMG_API+'/images/qianbao.png'" size="64"></u-icon>
						<u-icon v-if="item == '微信支付'" :name="$_BASE_IMG_API+'/images/weixin.png'" size="64"></u-icon>
						<u-icon v-if="item == '支付宝支付'" :name="$_BASE_IMG_API+'/images/zhifubao.png'" size="64"></u-icon>
						<u-icon v-if="item == '抵用券支付'" :name="$_BASE_IMG_API+'/images/qianbao.png'" size="64"></u-icon>
						
					</view>
					<text class="u-m-l-30 u-font-26">{{item}}</text>
				</view>
				<u-radio-group v-model="value">
					<u-radio active-color="var(--mainColor)" :name="index"></u-radio>
				</u-radio-group>
			</view>
		</view>

		<view class="position-fixed u-p-l-24" style="bottom: 48rpx;left: 0rpx;">
			<dy-button width="702rpx" height='88rpx' backgroundColor="var(--mainColor)" borderColor="var(--mainColor)"
				size="medium" @click="payBtn" :isLoading="isLoading">立即支付</dy-button>
		</view>
		<dy-pass-popup ref="passPopup" @confirm="confirm"></dy-pass-popup>
		<web-view v-if="pay_url" :src="pay_url"></web-view>
	</view>
</template>

<script>
	// #ifdef MP-WEIXIN
	// const DGBillPlugin = requirePlugin('dg-bill');
	// #endif
	import {
		GoodsCenterApi,
		GroupCenterApi,
		SeckillCenterApi,
		BaseCenterApi
	} from '@/api/serves.js'
	export default {
		data() {
			return {
				// #ifdef MP-WEIXIN
				list: ['余额支付', '微信支付', '抵用券支付'],
				// #endif
				// #ifndef MP-WEIXIN
				list: ['余额支付', '微信支付', '抵用券支付', '支付宝支付'],
				// #endif
				value: '0',
				time: 5,
				timestamp: '',
				order_no: '',
				pay_price: '',
				from: '', //  common，cart，group
				// from: '', // 支付类型 1普通，2拼团，3秒杀
				isLoading: false,
				pre_order_id: '', //斗拱预下单id
				pay_url: ''
			}
		},
		onShow() {
			if (this.isLogin) this.$store.dispatch('user/getUserInfo')
			this.payError()
		},
		async onLoad(options) {
			console.log('option', options);
			let info = JSON.parse(options.orderInfo)
			this.order_no = info.order_no
			this.from = info.from
			this.pre_order_id = info.pre_order_id
			console.log('info', info);
			if (info.sign) {
				this.weixinPay(info)
			} else {
				this._orderDetail()
			}
		},
		methods: {
			// app跳转小程序支付
			weixinPay(info) {
				// DGBillPlugin.requestPay(this.pre_order_id, this.paySuccess, this.payError)
				// wx.navigateToMiniProgram({
				//   appId: 'wx11361ccf7f47b948',//固定填写斗拱账单小程序
				//   path: '/pages/cashier/cashier?p=' + this.pre_order_id
				// })
				wx.requestPayment({
					...info,
					"prepayid": info.package.split('=')[1], // 统一下单订单号
					"sign": "MD5", // 签名，这里用的 MD5/RSA 签名
					success: this.paySuccess,
					fail: (err) => {
						console.log(err)
					}
				})
			},
			_orderDetail() {
				this.$ShowLoading()
				GoodsCenterApi.orderDetail({
					order_no: this.order_no
				}).then(res => {
					this.$HideLoading()
					console.log('订单详情', res);
					if (res.code == 1) {
						let orderInfo = res.data.order
						this.pay_price = orderInfo.pay_price
						// if(this.isAppBack == 1) this._otherPay()
						if (orderInfo.duetime > 0) return this.timestamp = orderInfo.duetime // 订单未失效
						this.$u.toast('订单已失效，5秒后返回！', 5000) // 订单已失效
						let timer = setInterval(() => {
							this.time--
							if (this.time == 0) {
								clearInterval(timer)
								uni.navigateBack()
							}
						}, 1000)
					} else {
						this.$Toast(res.msg)
					}
				})
			},
			end() {
				uni.navigateTo()
			},
			back() {
				let timeDiff = this.$refs.uCountDown.seconds
				let hour = parseInt((timeDiff % 86400) / 3600);
				let minute = parseInt((timeDiff % 3600) / 60);
				let sec = parseInt((timeDiff % 3600) % 60);
				uni.showModal({
					title: '提示',
					content: `您的订单在 ${hour} 时 ${minute} 分 ${sec} 秒内未支付将被取消，尽快完成支付`,
					cancelText: '确认离开',
					confirmText: '继续支付',
					success: (res) => {
						if (res.cancel) {
							uni.navigateBack()
						}
					}
				})
			},
			payBtn() {
				console.log('pay', this.value);
				switch (this.value - 0) {
					case 0:
						this.$refs.passPopup.open()
						break;
					case 1:
						this._otherPay()
						break;
					case 2:
						this.$refs.passPopup.open()
						break;
					case 3:
						this.aliPay()
						break;
					
					default:
						console.log('不存在执行这里');
						break;
				}
			},
			// 余额支付
			confirm(paypwd) {
				uni.showLoading()
				this.isLoading = true
				if (this.from == 'common' || this.from == 'cart') {
					if (this.value==2) {
						return this._dyjpay(paypwd) // 商品抵用券支付
					} else {
						return this._yuepay(paypwd) // 商品余额支付
					}
					
				}				
				
				if (this.from == 'group') return this._groups_pay(paypwd) // 拼团订单支付
				if (this.from == 'seckill') return this._seckill_pay(paypwd) // 秒杀订单支付
			},
			_yuepay(paypwd) {
				GoodsCenterApi.yuepay({
					order_no: this.order_no,
					paypwd
				}).then(res => {
					this.formartRes(res)
				})
			},
			_dyjpay(paypwd) {
				GoodsCenterApi.dyjpay({
					order_no: this.order_no,
					paypwd
				}).then(res => {
					this.formartRes(res)
				})
			},
			_groups_pay(paypwd) {
				GroupCenterApi.groups_pay({
					order_no: this.order_no,
					paypwd
				}).then(res => {
					this.formartRes(res)
				})
			},
			_seckill_pay(paypwd) {
				SeckillCenterApi.orderskill_pay({
					order_no: this.order_no,
					paypwd
				}).then(res => {
					this.formartRes(res)
				})
			},
			formartRes(res) {
				uni.hideLoading()
				console.log('支付结果', res);
				this.isLoading = false
				if (res.code == 1) {
					this.$refs.passPopup.close()
					uni.redirectTo({
						url: '/pages/goodsDetail/goodsOrderPaySuccess/goodsOrderPaySuccess?' +
							`from=${this.from}&price=${this.pay_price}`
					})
				} else {
					this.$Toast(res.msg)
				}
			},
			paySuccess() {
				console.log('成功隐藏');
				this.isLoading = false
				uni.hideLoading()
				if (this.pre_order_id) {
					uni.redirectTo({
						url: '/pages/goodsDetail/goodsOrderPayComplate/goodsOrderPayComplate?type=1'
					})
				} else {
					uni.redirectTo({
						url: '/pages/order/mineOrderList/mineOrderList?type=2'
					})
				}
				console.log('跳转到待发货页面');
			},
			payError() {
				console.log('失败隐藏');
				this.isLoading = false
				uni.hideLoading()
				if (this.pre_order_id) {
					uni.redirectTo({
						url: '/pages/goodsDetail/goodsOrderPayComplate/goodsOrderPayComplate?type=0'
					})
				}
			},
			_otherPay() {
				this.isLoading = true
				let params = {
					order_no: this.order_no,
					// pay_type: this.value == 1?'wechat':'alipay',
					pay_type: this.list[this.value] == '支付宝支付' ? 'alipay' : 'wechat',
					order_type: 10,
					// #ifdef APP-PLUS
					pay_method: "app"
					// #endif
					// #ifdef H5
					pay_method: "wap"
					// #endif
					// #ifdef MP-WEIXIN
					pay_method: "miniapp"
					// #endif
				}
				uni.showLoading({
					title: '支付中...'
				})

				// #ifdef MP-WEIXIN
				console.log(params);
				if (params.pay_type === 'wechat') { //使用斗拱插件调支付页面
					BaseCenterApi.huifuWxPay(params).then(res => {
						// DGBillPlugin.requestPay(res.data.pre_order_id, this.paySuccess, this.payError)
						console.log(res);
						// wx.navigateToMiniProgram({
						//   appId: 'wx11361ccf7f47b948',//固定填写斗拱账单小程序
						//   path: '/pages/cashier/cashier?p=' + res.data.pre_order_id
						// })
						if (res.code == 0) {
							this.$Toast(res.msg)
							this.isLoading = false
						} else {
							wx.requestPayment({
								...res.data,
								"prepayid": res.data.package.split('=')[1], // 统一下单订单号
								"sign": "MD5", // 签名，这里用的 MD5/RSA 签名
								success: this.paySuccess,
								fail: (err) => {
									console.log(err)
								}
							})
						}
					})
					return
				}
				// #endif
				// #ifdef APP-PLUS
				console.log('app');
				//跳转小程序支付
				plus.share.getServices(res => {
					this.sweixin = res.find(i => i.id === 'weixin')
					console.log(this.sweixin);
					if (this.sweixin) {
						// 分享跳转到微信小程序
						let params = {
							order_no: this.order_no,
							order_type: 10,
						}
						BaseCenterApi.huifuWxPay(params).then(res => {
							console.log(res, 'res');
							if (res.code == 0) {
								uni.hideLoading()
								this.isLoading = false
								this.$Toast(res.msg)
								return
							}
							uni.hideLoading()
							// params.pre_order_id = res.data.pre_order_id
							let info = {
								...res.data,
								"prepayid": res.data.package.split('=')[1], // 统一下单订单号
								"sign": "MD5", // 签名，这里用的 MD5/RSA 签名
								// pre_order_id:111
							}
							this.sweixin.launchMiniProgram({
								id: 'gh_7332f30f32d0', // 	关联微信小程序的原始ID（"g_"开头的字符串）
								path: "pages/goodsDetail/goodsOrderPay/goodsOrderPay?orderInfo=" +
									JSON.stringify(info), //	打开小程序的页面路径，不传默认跳转首页
								type: 0 // 	微信小程序版本类型，可取值： 0-正式版； 1-测试版； 2-体验版。 默认值为0。
							}, res => {
								this.isLoading = false
								console.log('成功唤起微信小程序');
							}, err => {
								this.isLoading = false
								console.log('失败');
							})
						})
					} else {
						// 没有获取到微信分享服务
						this.isLoading = false
						console.log('没有获取到微信分享服务');
					}
				}, err => {
					// 获取分享服务列表失败
					this.isLoading = false
					console.log('获取分享服务列表失败');
				});
				// #endif
			},
			//app支付宝支付
			aliPay() {
				this.isLoading = true
				let params = {
					order_no: this.order_no,
					// pay_type: this.value == 1?'wechat':'alipay',
					pay_type: this.list[this.value] == '支付宝支付' ? 'alipay' : 'wechat',
					order_type: 10,
					// #ifdef APP-PLUS
					pay_method: "app"
					// #endif
					// #ifdef H5
					pay_method: "wap"
					// #endif
					// #ifdef MP-WEIXIN
					pay_method: "miniapp"
					// #endif
				}
				uni.showLoading({
					title: '支付中...'
				})
				console.log('params', params);
				BaseCenterApi.huifuPay(params).then(res => {
					console.log('支付', res);
					this.isLoading = false
					if (res.code == 1) {
						// #ifdef H5
						//将接口返回的Form表单显示到页面
						document.querySelector('body').innerHTML = res;
						//调用submit 方法
						document.forms[0].submit()
						// #endif
						if (res.data.qr_code) {
							let data = res.data.qr_code // 莫名其妙，这行注释掉就跳不过去了
							console.log('跳转支付宝支付', data);
							this.pay_url = res.data.qr_code
						} else {
							this.$HideLoading()
							this.$Toast("跳转支付宝失败")
						}
					} else {
						this.$HideLoading()
						this.$u.toast(res.msg)
					}
				})
			},
			// H5支付宝支付
			payForH5() {
				window.location.href =
					`${this.$_baseUrl}/api/vip/buy?vip_id=${this.vipCard[this.key].id}&pay_method=wap&pay_type=${this.radio}`
			},
		}
	}
</script>

<style lang="scss" scoped>
	::v-deep .u-countdown-item {
		padding: 5rpx 15rpx;
	}
</style>